<template>
  <div class="product-detail-container">
    <!-- 顶部信息 大哥通天带 共有-->
    <div class="top-info">
      <div class="product-image">
        <img
          v-if="form.productsimg"
          :src="form.productsimg"
          class="avatar"
          width="100px"
        />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </div>
      <div class="product-basic">
        <h3 style="font-size: 30px">{{ form.shoopsName }}</h3>
        <p>
          <span>生产批次：{{ form.batchId }}</span>
        </p>
        <p>
          <span>保质期：{{ form.shelflife }} </span> 天
        </p>
        <p>生产许可证号：{{ form.productionnumber }}</p>
        <p>生产企业：{{ form.manufacturers }}</p>
        <h4>产品检验报告</h4>

        <div class="report-section">
          <h4>产品检验报告</h4>
          <el-upload
            v-model:file-list="fileList"
            action="https://localhost:7238/api/UpLoad/UploadImages"
            list-type="picture-card"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            class="upload-demo"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>
      </div>
      <div class="action-buttons">
        <el-button type="primary" size="small">修改基本信息</el-button>
        <el-button type="primary" size="small">导出溯源码</el-button>
      </div>
    </div>

    <!-- 标签页1 -->
    <el-tabs v-model="activeTab" type="card">
      <!-- #region  养殖信息 -->
      <!-- 养殖信息 -->
      <el-tab-pane label="养殖信息 (5/5)" name="养殖信息">
        <h4 style="color: blue">
          养殖信息
          <button style="color: black" @click="FarmFantian">设置</button>
        </h4>

        <div class="breeding-info">
          <el-row>
            <el-col span="12">
              <div class="info-item">
                <span>品种：{{ breedingInfo.variety }}</span>
                <!-- <span>{{ breedingInfo.variety }}</span> -->
              </div>
              <div class="info-item">
                <span>来源：</span>
                <span>{{ breedingInfo.source }}</span>
              </div>
              <div class="info-item">
                <span>饲养天数：</span>
                <span>{{ breedingInfo.rearsNum }} 天</span>
              </div>
              <div class="info-item">
                <span>饲料品牌：</span>
                <span>{{ breedingInfo.feedbrands }}</span>
              </div>
            </el-col>
            <el-col span="12">
              <div class="info-item">
                <span>饲养负责人：</span>
                <span>{{ breedingInfo.feedPerson }}</span>
              </div>
              <div class="info-item">
                <span>出栏日期：</span>
                <span>{{ breedingInfo.slaughterTime }}</span>
              </div>
            </el-col>
          </el-row>

          <!-- 保健信息 addHealthRow-->

          <div>
            <el-container>
              <el-header>
                <span style="font-size: 18px; font-weight: bold; color: #000000"
                  >免疫信息</span
                >
                <el-button @click="addRow">新增行</el-button>
              </el-header>
              <el-main>
                <div>
                  <el-table :data="tableData" border>
                    <el-table-column label="饲养天数">
                      <template #default="scope">
                        <el-input
                          v-if="scope.row.isEditing"
                          v-model="scope.row.rearsNum"
                          :placeholder="scope.row.rearsNum"
                          @blur="validateFeedDays(scope.row)"
                          style="width: 80px"
                        />
                        <span v-else>{{ scope.row.rearsNum }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="保健方式">
                      <template #default="scope">
                        <el-input
                          v-if="scope.row.isEditing"
                          v-model="scope.row.healthmodas"
                          :placeholder="scope.row.healthmodas"
                          @blur="validateHealthMethod(scope.row)"
                          style="width: 120px"
                        />
                        <span v-else>{{ scope.row.healthmodas }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="保健方法">
                      <template #default="scope">
                        <el-input
                          v-if="scope.row.isEditing"
                          v-model="scope.row.healthmethods"
                          :placeholder="scope.row.healthmethods"
                          @blur="validateHealthWay(scope.row)"
                          style="width: 120px"
                        />
                        <span v-else>{{ scope.row.healthmethods }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button
                          v-if="!scope.row.isEditing"
                          type="text"
                          size="small"
                          @click="editRow(scope.row)"
                        >
                          修改
                        </el-button>
                        <el-button
                          v-if="!scope.row.isEditing"
                          type="text"
                          size="small"
                          @click="deleteHealthRow(scope.row)"
                        >
                          删除
                        </el-button>
                        <el-button
                          v-if="scope.row.isEditing"
                          type="text"
                          size="small"
                          @click="saveRow(scope.row)"
                        >
                          保存
                        </el-button>
                        <el-button
                          v-if="scope.row.isEditing"
                          type="text"
                          size="small"
                          @click="cancelEdit(scope.row)"
                        >
                          取消
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-main>
            </el-container>
          </div>
          <!-- 新增 保健 -->
          <!--     <div>
            <el-dialog
              v-model="dialog.dialoghealth"
              :title="dialog.title"
              width="500"
            >
              <el-form :model="Health">
                <el-form-item label="饲养天数" :label-width="formLabelWidth">
                  <el-input v-model="Health.rearsNum" autocomplete="off" />
                </el-form-item>
                <el-form-item label="保健方式" :label-width="formLabelWidth">
                  <el-input v-model="Health.healthmodas" autocomplete="off" />
                </el-form-item>
                <el-form-item label="保健方法" :label-width="formLabelWidth">
                  <el-input v-model="Health.healthmethods" autocomplete="off" />
                </el-form-item>
              </el-form>
              <template #footer="scope">
                <div class="dialog-footer">
                  <el-button @click="dialogFormVisible = false"
                    >Cancel</el-button
                  >
                  <el-button type="primary" @click="editHealthRow(scope.row)">
                    Confirm
                  </el-button>
                </div>
              </template>
            </el-dialog>
          </div> -->

          <!-- 动检 -->
          <div class="inspection">
            <h4>动检</h4>

            <el-form-item>
              <!-- <el-input v-model="form.productsimg" /> -->
              <el-upload
                v-model:file-list="fileDynamicList"
                action="https://localhost:7238/api/UpLoad/UploadDynamicImages"
                list-type="picture-card"
                :auto-upload="true"
                :multiple="false"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </div>
          <!-- 企业信息 -->
          <div class="enterprise-info">
            <h4 style="color: blue">
              企业信息
              <button style="color: black" @click="companysFantian">
                设置
              </button>
            </h4>
            <!-- 显示企业信息 -->
            <div class="info-item">
              <span>养殖场：</span>
              <span>{{ CompanysLists.farms }}</span>
            </div>
            <div class="info-item">
              <span>负责人：</span>
              <span>{{ CompanysLists.head }}</span>
            </div>
            <div class="info-item">
              <span>存栏数量：</span>
              <span>{{ CompanysLists.stocksNumber }} 只</span>
            </div>
          </div>

          <!-- 企业照片 -->
          <div class="enterprise-photo">
            <h4>企业照片</h4>
            <el-form-item>
              <!-- <el-input v-model="form.productsimg" /> -->
              <el-upload
                v-model:file-list="fileCorporateList"
                action="https://localhost:7238/api/UpLoad/UploadCorporateImages"
                list-type="picture-card"
                :auto-upload="true"
                :multiple="false"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </div>

          <!-- 新增养殖信息 -->
          <div>
            <el-dialog
              v-model="dialogFormVisible"
              title="Shipping address"
              width="500"
            >
              <el-form :model="Farms">
                <el-form-item label="品种" :label-width="formLabelWidth">
                  <el-input v-model="Farms.variety" autocomplete="off" />
                </el-form-item>
                <el-form-item label="来源" :label-width="formLabelWidth">
                  <el-input v-model="Farms.source" autocomplete="off" />
                </el-form-item>
                <el-form-item label="饲养天数" :label-width="formLabelWidth">
                  <el-input v-model="Farms.rearsNum" autocomplete="off" />
                </el-form-item>
                <el-form-item label="饲养品牌" :label-width="formLabelWidth">
                  <el-input v-model="Farms.feedbrands" autocomplete="off" />
                </el-form-item>
                <el-form-item label="饲养负责人" :label-width="formLabelWidth">
                  <el-input v-model="Farms.feedPerson" autocomplete="off" />
                </el-form-item>
                <el-form-item label="出栏日期" :label-width="formLabelWidth">
                  <el-date-picker
                    type="date"
                    v-model="Farms.slaughterTime"
                  ></el-date-picker>
                </el-form-item>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="dialogFormVisible = false"
                    >Cancel</el-button
                  >
                  <el-button type="primary" @click="CreateFarms">
                    保存
                  </el-button>
                </div>
              </template>
            </el-dialog>
          </div>

          <!-- 新增企业信息 -->
          <el-dialog
            v-model="dialogCompanysVisible"
            title="Shipping address"
            width="500"
          >
            <el-form :model="companys">
              <el-form-item label="养殖场" :label-width="formLabelWidth">
                <el-input v-model="companys.farms" autocomplete="off" />
              </el-form-item>
              <el-form-item label="负责人" :label-width="formLabelWidth">
                <el-input v-model="companys.head" autocomplete="off" />
              </el-form-item>
              <el-form-item label="存栏数量(值)" :label-width="formLabelWidth">
                <el-input v-model="companys.stocksNumber" autocomplete="off" />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogCompanysVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="CreateCompanys">
                  保存
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </el-tab-pane>

      <!-- #endregion   -->

      <!-- 其他标签页类似结构 -->
      <!-- -----------------------------------------  屠宰信息  ------------------------------------------ -->
      <!-- #region  屠宰信息 -->
      <!-- 屠宰信息 -->
        <el-tab-pane label="屠宰信息 (5/5)" name="屠宰信息">
        <h4 style="color: blue">
          屠宰信息
          <button style="color: black" @click="SlaughterFantian">设置</button>
        </h4>
        <div class="breeding-info">
          <el-row>
            <el-col span="10">
              <div class="info-item">
                <span>批次:{{ Slaughterss.producbatche }}</span>
                <!-- <span>{{ breedingInfo.variety }}</span> -->
              </div>
              <div class="info-item">
                <span>到厂均重:</span>
                <span>{{ Slaughterss.factoryWeight }}公斤</span>
              </div>
              <div class="info-item">
                <span>到厂时间:</span>
                <span>{{ Slaughterss.factoryTime }} </span>
              </div>
              <div class="info-item">
                <span>屠宰时间:</span>
                <span>{{ Slaughterss.slaughterTime }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="report-section">
          <h4>相关资质</h4>
          <el-upload
            v-model:file-list="fileListSlaughter"
            action="https://localhost:7238/api/UpLoad/UploadQualificationsImages"
            list-type="picture-card"
            :on-remove="handleSlaughterRemove"
            :on-success="handleSlaughterUploadSuccess"
            class="upload-demo"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>

        <!-- 企业信息 -->
        <div class="enterprise-info">
          <h4 style="color: blue">
            企业信息
            <button style="color: black" @click="firmFantian">
              设置
            </button>
          </h4>
          <!-- 显示屠宰企业信息   firm -->
          <div class="info-item">
            <span>公司名称：</span>
            <span>{{ firmss.companyName }}</span>
          </div>
          <div class="info-item">
            <span>成立时间：</span>
            <span>{{ firmss.foundedtime }}</span>
          </div>
          <div class="info-item">
            <span>公司地址：</span>
            <span>{{ firmss.companyAddres }} </span>
          </div>
          <div class="info-item">
            <span>公司简介：</span>
            <span>{{ firmss.companyinfo }} </span>
          </div>
        </div>

        <!-- 屠宰企业照片 -->
        <div class="enterprise-photo">
          <h4>企业照片</h4>
          <el-form-item>
            <!-- <el-input v-model="form.productsimg" /> -->
            <el-upload
              v-model:file-list="falseSlaughterFirms"
              action="https://localhost:7238/api/UpLoad/UploadSlaughterFirmsFilesImages"
              list-type="picture-card"
              :auto-upload="true"
              :multiple="false"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleSlaughterFirmsRemove"
              :on-success="handleSlaughterFirmsUploadSuccess"
              :before-upload="beforeUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 新增屠宰信息 -->
        <div>
          <el-dialog
            v-model="dialogSlaughtersVisible"
            title="Shipping address"
            width="500"
          >
            <el-form :model="Slaughter">
              <el-form-item label="批次" :label-width="formLabelWidth">
                <el-input v-model="Slaughter.Producbatche" autocomplete="off" />
              </el-form-item>
              <el-form-item
                label="到厂均重(公斤)"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model="Slaughter.factoryWeight"
                  autocomplete="off"
                />
              </el-form-item>

              <el-form-item label="到厂时间" :label-width="formLabelWidth">
                <el-date-picker
                  type="date"
                  v-model="Slaughter.factoryTime"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="屠宰时间" :label-width="formLabelWidth">
                <el-date-picker
                  type="date"
                  v-model="Slaughter.slaughterTime"
                ></el-date-picker>
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogSlaughtersVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="CreateSlaughter">
                  保存
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>

        <!-- 新增公司信息 -->
        <div>
          <el-dialog
            v-model="dialogfirmVisible"
            title="Shipping address"
            width="500"
          >
            <el-form :model="firms">
              <el-form-item label="公司名称:" :label-width="formLabelWidth">
                <el-input v-model="firms.companyName" autocomplete="off" />
              </el-form-item>

              <el-form-item label="成立时间:" :label-width="formLabelWidth">
                <el-date-picker
                  type="date"
                  v-model="firms.foundedtime"
                ></el-date-picker>
              </el-form-item>

              <el-form-item label="所在地址" prop="name">
                <el-cascader
                  size="large"
                  :options="options"
                  v-model="provinces"
                  @change="handleChange"
                  placeholder="请选择省市区"
                  style="width: 300px"
                />
              </el-form-item>

              <el-form-item label="公司简介:" :label-width="formLabelWidth">
                <el-input
                  v-model="firms.companyinfo"
                  autocomplete="off"
                  type="textarea"
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogSlaughtersVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="createFirm"> 保存 </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
        <!-- #endregion -->
      </el-tab-pane>

      <!-- -------------------------------------------  深加工信息  ------------------------------------------ -->
      <!-- #region 深加工信息 -->
      <el-tab-pane label="深加工信息(5/5)" name="深加工信息（0/5）">
        <el-button type="primary" size="small">深加工信息</el-button>
        <h4 style="color: blue">
          屠宰信息
          <button style="color: black" @click="processFantian">设置</button>
        </h4>
        <div class="breeding-info">
          <el-row>
            <el-col span="10">
              <div class="info-item">
                <span>班组:{{ ProcessList.team }}</span>
                <!-- <span>{{ breedingInfo.variety }}</span> -->
              </div>
              <div class="info-item">
                <span>负责人:</span>
                <span>{{ ProcessList.head }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
     
       <div class="report-section">
          <h4 style="color: blue;">食品安全信息</h4>
          <el-upload
            v-model:file-list="falseProcessFirms"
            action="https://localhost:7238/api/UpLoad/UploadProcessFirmsFilesImages"
            list-type="picture-card"
            :on-remove="handleSlaughterRemove"
            :on-success="handleProcessUploadSuccess"
            class="upload-demo"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>

        <!-- 新增深加工 -->
        <div>
          <el-dialog
            v-model="dialogProcessfirmVisible"
            title="Shipping address"
            width="500"
          >
            <el-form :model="process">
              <el-form-item label="班组:" :label-width="formLabelWidth">
                <el-input v-model="process.team" autocomplete="off" />
              </el-form-item>
              <el-form-item label="负责人:" :label-width="formLabelWidth">
                <el-input v-model="process.head" autocomplete="off" />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="dialogSlaughtersVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="createProcess">
                  保存
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>

      </el-tab-pane>

      <!-- #endregion  -->
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElTable, ElMessageBox } from "element-plus";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile, UploadFile } from "element-plus";
import type { TableInstance } from "element-plus";

const multipleTableRef = ref<TableInstance>();
const multipleSelection = ref<any[]>([]);
const store = useCounterStore();

const router = useRouter();
const route = useRoute();

const form = reactive({
  productsId: 0,
  shoopId: 0,
  batchId: 0,
  shelflife: 0,
  productionnumber: "",
  manufacturers: "",
  productsimg: "",
  createName: store.ccstore.userName,
  createTime: new Date(),
  updateName: "",
  updateTime: new Date(),
  isDel: true,
  shoopsName: "",
});

onMounted(() => {
  getBacthProducts();
  getShoops();
});

const getBacthProducts = () => {
  axios
    .get("https://localhost:7203/api/Farms/GetFarmsByBatchId", {
      params: {
        BatchId: route.query.BatchId,
      },
    })
    .then((res) => {
      if (res.data.code == 200) {
        console.log(res.data, "44");
        const data = res.data.data[0];
        form.productsimg = data.productsimg;
        form.shoopId = data.shoopId;
        form.batchId = data.batchId;
        form.shelflife = data.shelflife;
        form.productionnumber = data.productionnumber;
        form.manufacturers = data.manufacturers;
        form.shoopsName = data.shoopsName;
      }
    });
};

const imageUrl = ref("");

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
// 图片预览
const handlePictureCardPreview = (file: { url: string }) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log(response);
  form.productsimg = imageUrl.value;
  imgs.value.imgType = imageUrl.value;
  form.productsimg = response;
  imgs.value.imgType = response;
};

const shoops = ref([]);

const getShoops = () => {
  axios.get("http://localhost:5103/api/Traceability/QueryShoop").then((res) => {
    shoops.value = res.data.data;
  });
};

const activeTab = ref("养殖信息");
//#region   养殖信息
// 养殖信息

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const Farms = reactive({
  farmsId: 0,
  batchId: route.query.BatchId,
  variety: "",
  source: "",
  rearsNum: 0,
  feedPerson: "",
  feedbrands: "",
  slaughterTime: null,
  isDel: true,
});

const breedingInfo = reactive({
  farmsId: 0,
  batchId: route.query.BatchId,
  variety: "",
  source: "",
  rearsNum: 0,
  feedPerson: "",
  feedbrands: "",
  slaughterTime: null,
  isDel: true,
});

const FarmFantian = () => {
  dialogFormVisible.value = true;
  getFarm;
  CreateFarms;
};

onMounted(() => {
  getIntegrateImg();
  getDynamicIntegrateImg();
  getCorporateIntegrateImg();
  getSlaughterIntegrateImg();
  getFarm();

  getHealth();
  getCompanys();

  getSlaughter();

  getFirms();
  getSlaughterFirmsIntegrateImg();

  getProcessList();

  getProcessFirmsIntegrateImg();
});

// 获取养殖信息
const getFarm = () => {
  // alert(route.query.BatchId);
  axios
    .get("https://localhost:7203/api/Farms/GetFarm", {
      params: {
        batchId: route.query.BatchId,
      },
    })
    .then((res) => {
      console.log(res.data.data[0], "77777");
      if (res.data.code == 200) {
        var data = res.data.data[0];
        breedingInfo.farmsId = data.farmsId;
        breedingInfo.batchId = data.batchId;
        breedingInfo.variety = data.variety;
        breedingInfo.source = data.source;
        breedingInfo.rearsNum = data.rearsNum;
        breedingInfo.feedbrands = data.feedbrands;
        breedingInfo.feedPerson = data.feedPerson;
        breedingInfo.slaughterTime = data.slaughterTime.substring(0, 10);

        Farms.farmsId = data.farmsId;
        Farms.batchId = data.batchId;
        Farms.variety = data.variety;
        Farms.source = data.source;
        Farms.rearsNum = data.rearsNum;
        Farms.feedbrands = data.feedbrands;
        Farms.feedPerson = data.feedPerson;
        Farms.slaughterTime = data.slaughterTime.substring(0, 10);
      } else {
        breedingInfo.farmsId = 0;

        breedingInfo.batchId = "";
        breedingInfo.variety = "";
        breedingInfo.source = "";
        breedingInfo.rearsNum = 0;
        breedingInfo.feedbrands = "";
        breedingInfo.feedPerson = "";
        breedingInfo.slaughterTime = null;

        Farms.farmsId = 0;
        Farms.batchId = "";
        Farms.variety = "";
        Farms.source = "";
        Farms.rearsNum = 0;
        Farms.feedbrands = "";
        Farms.feedPerson = "";
        Farms.slaughterTime = null;
      }
    });
};

//添加养殖
const CreateFarms = () => {
  // dialogFormVisible.value = true;
  axios
    .post("https://localhost:7238/api/Farms/CreateFarm", Farms)
    .then((res) => {
      if (res.data.code == 100) {
        ElMessage.success(res.data.msg);
        getFarm();
        dialogFormVisible.value = false;

        return;
      } else if (res.data.code == 206) {
        ElMessage.success(res.data.msg);
        getFarm();
        dialogFormVisible.value = false;
        return;
      } else {
        ElMessage.error("失败");
      }
    });
};

// 保健信息
const tableData: any = ref([]);

//保健信息数据类型
interface ImmuneRow {
  healthId: number;
  batchId: number;
  rearsNum: number;
  healthmodas: string;
  healthmethods: string;
  updateName: string;
  updateTime: string;
  isEditing: boolean;
}

//新增保健信息
const dialog = reactive({
  dialoghealth: false,
  title: "",
  IsAdd: true,
});

// 新增行
const addRow = () => {
  tableData.value.push({
    healthId: 0,
    batchId: 0,
    rearsNum: "",
    healthmodas: "",
    healthmethods: "",
    isEditing: true,
  });
};
console.log(tableData.value);

//是否执行添加方法
const add = ref(false);
// 编辑行
const editRow = (row: ImmuneRow) => {
  row.isEditing = true;
  add.value = true;
  console.log(add.value);
};

// 保存行
const saveRow = (row: any) => {
  row.batchId = route.query.BatchId;
  // alert(row.batchId);
  if (!row.rearsNum) {
    ElMessage.warning("请填写饲养天数");
    return;
  }
  if (!row.healthmodas) {
    ElMessage.warning("请填写保健方式");
    return;
  }
  if (!row.healthmethods) {
    ElMessage.warning("请填写保健方法");
    return;
  }
  if (add.value == false) {
    // 这里可以添加保存到后端的逻辑，比如调用axios发送请求
    axios({
      url: "https://localhost:7238/api/Healths/CreateHealth",
      method: "post",
      data: row,
    }).then((res) => {
      if (res.data.code == 100) {
        ElMessage.success(res.data.msg);
        getHealth();
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  } else {
    axios({
      url: "https://localhost:7238/api/Healths/UpdataHealth",
      method: "put",
      data: row,
    }).then((res) => {
      if (res.data.code == 206) {
        ElMessage.success(res.data.msg);
        getHealth();
        add.value = false;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  }
  row.isEditing = false;
};

// 取消编辑
const cancelEdit = (row: any) => {
  add.value = false;
  if (row.isEditing) {
    if (
      row.rearsNum === "" &&
      row.healthmodas === "" &&
      row.healthmethods === ""
    ) {
      const index = tableData.value.indexOf(row);
      if (index > -1) {
        tableData.value.splice(index, 1);
      }
    } else {
      row.isEditing = false;
    }
  }
  getHealth();
};

//显示免疫信息
const getHealth = () => {
  axios
    .get("https://localhost:7203/api/Health", {
      params: { BatchId: route.query.BatchId },
    })
    .then((res) => {
      console.log(res.data.data, "8000");
      tableData.value = res.data.data;
    });
};

//删除保健信息
const deleteHealthRow = (row: ImmuneRow) => {
  axios
    .put("https://localhost:7238/api/Healths/DelHealth", {
      healthId: row.healthId,
    })
    .then((res) => {
      if (res.data.code == 204) {
        ElMessage.success(res.data.msg);
        dialog.dialoghealth = false;
        return;
      } else {
        ElMessage.success(res.data.msg);
        dialog.dialoghealth = false;
        return;
      }
    });
  const index = tableData.value.indexOf(row);
  if (index > -1) {
    tableData.value.splice(index, 1);
  }
};

// 验证饲养天数
const validateFeedDays = (row: any) => {
  const input = row.rearsNum;
  if (input && isNaN(Number(input))) {
    ElMessage.warning("饲养天数只能输入数字");
    row.rearsNum = "";
  }
  if (input && input.toString().length > 5) {
    ElMessage.warning("饲养天数最多输入5位数字");
    row.rearsNum = input.toString().slice(0, 5);
  }
};

// 验证保健方式
const validateHealthMethod = (row: any) => {
  const input = row.healthmodas;
  if (input && /[^\u4e00-\u9fa5a-zA-Z]/.test(input)) {
    ElMessage.warning("保健方式不允许输入非特殊字符");
    row.healthmodas = input.replace(/[^\u4e00-\u9fa5a-zA-Z]/g, "");
  }
  if (input && input.length > 30) {
    ElMessage.warning("保健方式最多输入30位字符");
    row.healthmodas = input.slice(0, 30);
  }
};

// 验证保健方法
const validateHealthWay = (row: any) => {
  const input = row.healthmethods;
  if (input && /[^\u4e00-\u9fa5a-zA-Z]/.test(input)) {
    ElMessage.warning("保健方法不允许输入非特殊字符");
    row.healthmethods = input.replace(/[^\u4e00-\u9fa5a-zA-Z]/g, "");
  }
  if (input && input.length > 30) {
    ElMessage.warning("保健方法最多输入30位字符");
    row.healthmethods = input.slice(0, 30);
  }
};

// 企业信息

const dialogCompanysVisible = ref(false);

const companys = reactive({
  companyId: "",
  batchId: route.query.BatchId,
  head: "",
  farms: "",
  stocksNumber: "",
  isDel: true,
});

// 反填
const companysFantian = () => {
  dialogCompanysVisible.value = true;
  getCompanys;
  CreateCompanys;
};

//添加企业数据
const CreateCompanys = () => {
  dialogCompanysVisible.value = true;
  axios
    .post("https://localhost:7238/api/Companys/CreateCompanys", companys)
    .then((res) => {
      if (res.data.code == 100) {
        ElMessage.success(res.data.msg);
        getCompanys();
        dialogCompanysVisible.value = false;
        return;
      } else if (res.data.code == 206) {
        ElMessage.success(res.data.msg);
        getCompanys();
        dialogCompanysVisible.value = false;
        return;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};

const CompanysLists = ref({
  companyId: "",
  batchId: route.query.BatchId,
  head: "",
  farms: "",
  stocksNumber: "",
  isDel: true,
});
//获取企业数据
const getCompanys = () => {
  axios
    .get("https://localhost:7203/api/Companys/GetCompany", {
      params: {
        BatchId: route.query.BatchId,
      },
    })
    .then((res) => {
      console.log(res.data.data, "企业数据");
      if (res.data.code == 200 && res.data.data.length > 0) {
        CompanysLists.value.companyId = res.data.data[0].companyId || "";
        CompanysLists.value.farms = res.data.data[0].farms || "";
        CompanysLists.value.head = res.data.data[0].head || "";
        CompanysLists.value.stocksNumber = res.data.data[0].stocksNumber || "";

        companys.companyId = res.data.data[0].companyId || "";
        companys.farms = res.data.data[0].farms || "";
        companys.head = res.data.data[0].head || "";
        companys.stocksNumber = res.data.data[0].stocksNumber || "";
      } else {
        CompanysLists.value.farms = "";
        CompanysLists.value.head = "";
        CompanysLists.value.stocksNumber = "";
      }
    });
};

const imgs = ref({
  integrateImgsId: 0,
  batchId: route.query.BatchId?.toString() || "",
  imgType: "", // 改为存储单个字符串
  createName: store.ccstore.userName,
  createTime: "",
  imgName: "",
});

// 多图片上传
// 上传前校验（核心逻辑）

// 统一处理上传响应
const handleUploadSuccess = (response: any, uploadFile: UploadFile) => {
  console.log("完整响应:", response); // 调试关键点

  // 根据实际响应结构调整（常见情况处理）
  let imgUrl = "";
  let imgname = ""; //图片名称
  // 情况1：响应直接返回字符串URL
  if (typeof response === "string") {
    imgUrl = response;
    imgname = uploadFile.name;
  }
  // 情况2：响应为 { data: { url: ... } }
  else if (response?.data?.url) {
    imgUrl = response.data.url;
    // alert(imgUrl);
  }
  // 情况3：响应为 { url: ... }
  else if (response?.url) {
    imgUrl = response.url;
  }

  // 校验是否获取到有效URL
  if (imgUrl) {
    // alert(imgUrl);
    // 补全URL前缀（如果返回的是相对路径）
    if (!imgUrl.startsWith("http")) {
      imgUrl = `http://localhost:5004${imgUrl}`;
    }

    imgs.value.imgType = imgUrl;
    imgs.value.imgName = imgname;
    // 提交到后端
    submitToBackend();
  } else {
    ElMessage.error("无法解析图片地址");
  }
};

// 提交到业务接口
const submitToBackend = async () => {
  try {
    const res = await axios.post(
      "https://localhost:7238/api/Imgs/QueryInspec",
      {
        ...imgs.value,
        integrateImgsId: imgs.value.integrateImgsId,
        batchId: route.query.BatchId,
        imType: imgs.value.imgType,
        // imgName: imgs.value.imgName,

        createTime: new Date().toISOString(),
      }
    );

    // console.log("提交响应:", res.data); // 调试点
    if (res.data.success) {
      ElMessage.success("保存成功");
    }
  } catch (err) {
    console.error("提交错误:", err);
    ElMessage.error("保存失败");
  }
};

const fileList = ref([]);
// 显示产品检验报告图片信息
const getIntegrateImg = async () => {
  // alert(ImgType);
  await axios
    .get("https://localhost:7203/api/IntegrateImg/GetIntegrateImg", {
      params: {
        BatchId: route.query.BatchId?.toString() || "",
        ImgName: "产品检验",
      },
    })

    .then((res) => {
      // imagelist.value=res.data.dataco
      console.log(res.data.data.imgName, "产品检验报告图片");
      fileList.value = res.data.data.map((img: any) => ({
        url: img.imgType,
        id: img.integrateImgsId,
        data: { integrateImgsId: img.integrateImgsId }, // 将 imaId 存入 data
      }));
    });
};

//
const fileDynamicList = ref([]);
// 动检报告图片信息
const getDynamicIntegrateImg = () => {
  axios
    .get("https://localhost:7203/api/IntegrateImg/GetDynamicImg", {
      params: {
        BatchId: route.query.BatchId?.toString() || "",
        ImgName: "动检",
      },
    })

    .then((res) => {
      // imagelist.value=res.data.dataco
      console.log(res.data.data, "产品检验报告图片");
      fileDynamicList.value = res.data.data.map((img: any) => ({
        url: img.imgType,
        id: img.integrateImgsId,
        data: { integrateImgsId: img.integrateImgsId }, // 将 imaId 存入 data
      }));
    });
};

const fileCorporateList = ref([]);
// 企业报告图片信息
const getCorporateIntegrateImg = async () => {
  await axios
    .get("https://localhost:7203/api/IntegrateImg/GetCompanysImg", {
      params: {
        BatchId: route.query.BatchId?.toString() || "",
        ImgName: "企",
      },
    })

    .then((res) => {
      // imagelist.value=res.data.dataco

      console.log(res.data.data, "产品检验报告图片");
      fileCorporateList.value = res.data.data.map((img: any) => ({
        url: img.imgType,
        id: img.integrateImgsId,
        data: { integrateImgsId: img.integrateImgsId }, // 将 imaId 存入 data
      }));
    });
};
// 文件类型校验
const beforeUpload = (file: File) => {
  const isValidType = ["image/jpeg", "image/png"].includes(file.type);
  const isValidSize = file.size / 1024 / 1024 < 2;

  if (!isValidType) {
    ElMessage.error("只能上传JPG/PNG格式");
    return false;
  }
  if (!isValidSize) {
    ElMessage.error("图片不能超过2MB");
    return false;
  }
  return true;
};

//产品图片删除
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log("图片删除", uploadFile, uploadFiles);
  const integrateImgsId = uploadFile.data?.integrateImgsId;
  alert(integrateImgsId);
  DelImage(integrateImgsId);
};

const DelImage = (integrateImgsId: number) => {
  alert(integrateImgsId);
  axios
    .put("https://localhost:7238/api/Imgs/DelInspec", {
      integrateImgsId: integrateImgsId,
    })
    .then((res) => {
      if (res.data.code == 204) {
        ElMessage.success("删除成功");
        return;
      } else {
        ElMessage.success("删除失败");
        return;
      }
    });
};


//#endregion

//#region   屠宰信息
const dialogSlaughtersVisible = ref(false);
const Slaughter = ref({
  slaughterId: 0,
  batchId: route.query.BatchId ,
  producbatche: 0,
  factoryWeight: 0,
  factoryTime: "",
  slaughterTime: "",
  isDel: false,
});

const SlaughterFantian = () => {
  dialogSlaughtersVisible.value = true;
  getSlaughter;
  CreateSlaughter;
};
// 添加屠宰信息
const CreateSlaughter = () => {
  dialogSlaughtersVisible.value = true;

  axios
    .post(
      "https://localhost:7238/api/Slaughters/CreateSlaughters",
      Slaughter.value
    )
    .then((res) => {
      if (res.data.code == 100) {
        ElMessage.success(res.data.msg);
        // getCompanys();
        dialogSlaughtersVisible.value = false;
        return;
      } else if (res.data.code == 206) {
        ElMessage.success(res.data.msg);
        dialogSlaughtersVisible.value = false;
        return;
      } else {
        ElMessage.success(res.data.msg);
        dialogSlaughtersVisible.value = false;
      }
    });
};
const Slaughterss = reactive({
  slaughterId: 0,
  batchId:  route.query.BatchId ,
  producbatche: 0,
  factoryWeight: 0,
  factoryTime: "",
  slaughterTime: "",
  isDel: false,
});

//显示屠宰信息
const getSlaughter = () => {
  axios
    .get("https://localhost:7203/api/Slaughters/GetSlaughter", {
      params: { BatchId: route.query.BatchId },
    })
    .then((res) => {
      if (res.data.code == 200 && res.data.data.length > 0) {
        var data = res.data.data[0];
        Slaughterss.slaughterId = data.batchId;
        Slaughterss.batchId = data.batchId;
        Slaughterss.producbatche = data.producbatche;
        Slaughterss.factoryWeight = data.factoryWeight;
        Slaughterss.factoryTime = data.factoryTime.substring(0, 10);
        Slaughterss.slaughterTime = data.slaughterTime.substring(0, 10);
        Slaughterss.isDel = data.isDel;

        Slaughter.value.slaughterId = data.slaughterId;
        Slaughter.value.batchId = data.batchId;
        Slaughter.value.producbatche = data.producbatche;
        Slaughter.value.factoryWeight = data.factoryWeight;
        Slaughter.value.factoryTime = data.factoryTime.substring(0, 10);
        Slaughter.value.slaughterTime = data.slaughterTime.substring(0, 10);
        Slaughter.value.isDel = data.isDel;
      } else {
        Slaughterss.batchId = 0;
        Slaughterss.producbatche = 0;
        Slaughterss.factoryWeight = 0;
        Slaughterss.factoryTime = null;
        Slaughterss.slaughterTime = null;
        Slaughterss.isDel = null;
      }
    });
};

//产品图片删除  handleRemove
/* const handleSlaughterRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  // console.log("图片删除", uploadFile, uploadFiles);
  const integrateImgsId = uploadFile.data?.integrateImgsId;
  alert(integrateImgsId);
  DelImage(integrateImgsId);
}; */
// handleSlaughterFirmsRemove
const handleSlaughterRemove: UploadProps["onRemove"] = async (file) => {
  if (!file.data?.integrateImgsId) {
    // 防御性处理：数据未准备好时拦截删除
    // message.error("文件信息未就绪，请稍后重试");
    return false;
  }
  alert(file.data?.integrateImgsId);
  await DelImage(file.data.integrateImgsId);
  return true;
};

// 统一处理上传响应  handleUploadSuccess   handleSlaughterFirmsUploadSuccess
const handleSlaughterUploadSuccess = (
  response: any,
  uploadFile: UploadFile
) => {
  console.log("完整响应:", response); // 调试关键点

  // 根据实际响应结构调整（常见情况处理）
  let imgUrl = "";
  let imgname = ""; //图片名称
  // 情况1：响应直接返回字符串URL
  if (typeof response === "string") {
    imgUrl = response;
    imgname = uploadFile.name;
  }
  // 情况2：响应为 { data: { url: ... } }
  else if (response?.data?.url) {
    imgUrl = response.data.url;
    // alert(imgUrl);
  }
  // 情况3：响应为 { url: ... }
  else if (response?.url) {
    imgUrl = response.url;
  }

  // 校验是否获取到有效URL
  if (imgUrl) {
    // alert(imgUrl);
    // 补全URL前缀（如果返回的是相对路径）
    if (!imgUrl.startsWith("http")) {
      imgUrl = `http://localhost:5004${imgUrl}`;
    }

    imgs.value.imgType = imgUrl;
    imgs.value.imgName = imgname;
    // 提交到后端
    submitToBackend();
  } else {
    ElMessage.error("无法解析图片地址");
  }
};

const fileListSlaughter = ref([]);
// 显示相关资质图片信息
const getSlaughterIntegrateImg = () => {
  // alert(ImgType);
  axios
    .get("https://localhost:7203/api/IntegrateImg/GetQualificationsImg", {
      params: {
        BatchId: route.query.BatchId?.toString() || "",
        ImgName: "相关资质",
      },
    })

    .then((res) => {
      // imagelist.value=res.data.dataco
      console.log(res.data.data.imgName, "相关资质");
      fileListSlaughter.value = res.data.data.map((img: any) => ({
        url: img.imgType,
        id: img.integrateImgsId,
        data: { integrateImgsId: img.integrateImgsId }, // 将 imaId 存入 data
      }));
    });
};

// 企业信息
const firmFantian = () => {
  dialogfirmVisible.value = true;
  getFirms;
  createFirm;
}
const dialogfirmVisible = ref(false);

const firms = reactive({
  companyId: 0,
  batchId: route.query.BatchId,
  companyName: "",
  provinceId: 0,
  cityId: 0,
  countyId: 0,
  foundedtime: "",
  companyinfo: "",
  companyAddres: "",
});
import { regionData } from "element-china-area-data"; //引入

const options = regionData;
const provinces = ref([]);
const handleChange = (value: any) => {
  console.log(value);
  firms.provinceId = value[0];
  firms.cityId = value[1];
  firms.countyId = value[2];
  getCountyLabel(firms.provinceId, firms.cityId, firms.countyId);
};

// 提交企业信息
const createFirm = () => {
  axios
    .put("https://localhost:7238/api/Companys/CreateFirms", firms)
    .then((res) => {
      if (res.data.code == 100) {
        ElMessage.success(res.data.msg);
        // getCompanys();
        dialogfirmVisible.value = false;
        return;
      }else if (res.data.code == 206) {
        ElMessage.success(res.data.msg);
        dialogSlaughtersVisible.value = false;
        return;
      }  else {
        ElMessage.success(res.data.msg);
        dialogfirmVisible.value = false;
        return;
      }
    });
};

const firmss = reactive({
  companyId: 0,
  batchId: route.query.BatchId,
  companyName: "",
  provinceId: 0,
  cityId: 0,
  countyId: 0,
  foundedtime: "",
  companyinfo: "",
  companyAddres: "",
});

var name = ref("");
name.value = "四川锦祥食品有限公司";
// const name=ref("")
/* const checkCompanyName = () => {
 firmss.companyName= firms.companyName

} */

// 企业信息
const getFirms = () => {
 

  axios
    .get("https://localhost:7203/api/Companys/GetFirms", {
      params: {
        batchId: route.query.BatchId?.toString() || "",
        companyName: name.value,
      },
    })
    .then((res) => {
      const data = res.data.data[0];
      console.log(res.data.data[0], "3333");
      if (res.data.code == 200) {
        firmss.companyId = data.companyId;
        firmss.batchId = data.batchId;
        firmss.companyName = data.companyName;
        firmss.provinceId = data.provinceId;
        firmss.cityId = data.cityId;
        firmss.countyId = data.countyId;
        firmss.foundedtime = data.foundedtime;
        firmss.companyinfo = data.companyinfo;
        firmss.companyAddres = data.companyAddres;


       firms.companyId = data.companyId;
       firms.batchId = data.batchId;
       firms.companyName = data.companyName;
       firms.provinceId = data.provinceId;
       firms.cityId = data.cityId;
       firms.countyId = data.countyId;
       firms.foundedtime = data.foundedtime;
       firms.companyinfo = data.companyinfo;
       firms.companyAddres = data.companyAddres;

      } else {
       firms.companyId = 0;
        firmss.batchId = "";
        firmss.companyName = "";
        firmss.provinceId = 0;
        firmss.cityId = 0;
        firmss.countyId = 0;
        firmss.foundedtime = "";
        firmss.companyinfo = "";
        firmss.companyAddres = "";
      }
    });
};

// 企业图片
//
const handleSlaughterFirmsRemove: UploadProps["onRemove"] = async (file) => {
  if (!file.data?.integrateImgsId) {
    // 防御性处理：数据未准备好时拦截删除
    // message.error("文件信息未就绪，请稍后重试");
    return false;
  }
  alert(file.data?.integrateImgsId);
  await DelImage(file.data.integrateImgsId);
  return true;
};

// 统一处理上传响应  handleUploadSuccess
const handleSlaughterFirmsUploadSuccess = (
  response: any,
  uploadFile: UploadFile
) => {
  console.log("完整响应:", response); // 调试关键点

  // 根据实际响应结构调整（常见情况处理）
  let imgUrl = "";
  let imgname = ""; //图片名称
  // 情况1：响应直接返回字符串URL
  if (typeof response === "string") {
    imgUrl = response;
    imgname = uploadFile.name;
  }
  // 情况2：响应为 { data: { url: ... } }
  else if (response?.data?.url) {
    imgUrl = response.data.url;
    // alert(imgUrl);
  }
  // 情况3：响应为 { url: ... }
  else if (response?.url) {
    imgUrl = response.url;
  }

  // 校验是否获取到有效URL
  if (imgUrl) {
    // alert(imgUrl);
    // 补全URL前缀（如果返回的是相对路径）
    if (!imgUrl.startsWith("http")) {
      imgUrl = `http://localhost:5004${imgUrl}`;
    }

    imgs.value.imgType = imgUrl;
    imgs.value.imgName = imgname;
    // 提交到后端
    submitToBackend();
  } else {
    ElMessage.error("无法解析图片地址");
  }
};

const falseSlaughterFirms = ref([]);

// 显示屠宰信息企业图片信息
const getSlaughterFirmsIntegrateImg = () => {
  // alert(ImgType);
  axios
    .get("https://localhost:7203/api/IntegrateImg/GetSlaughterFirmsImg", {
      params: {
        BatchId: route.query.BatchId?.toString() || "",
        ImgName: "屠宰",
      },
    })

    .then((res) => {
      // imagelist.value=res.data.dataco
      console.log(res.data.data[0], "屠宰信息图片");
      falseSlaughterFirms.value = res.data.data.map((img: any) => ({
        url: img.imgType,
        id: img.integrateImgsId,
        data: { integrateImgsId: img.integrateImgsId }, // 将 imaId 存入 data
      }));
      console.log(falseSlaughterFirms.value, "屠宰信息图片1111");
    });
};

const laber = ""; //检测信息
const getCountyLabel = (
  provinceValue: number,
  cityValue: number,
  countyValue: number
) => {
  const province = regionData.find((item: any) => item.value == provinceValue);
  if (!province) return "--";
  const city = province.children?.find((item: any) => item.value == cityValue);
  if (!city) return "--";
  const county = city.children?.find((item: any) => item.value == countyValue);

  if (!county) {
    return "--";
  } else {
    firms.companyAddres = province.label + city.label + county.label;
  }
};
//#endregion

//#region  深加工

//反填深加工信息
const processFantian = () => {
  dialogProcessfirmVisible.value = true;
  getProcessList;
  createProcess;
};
const dialogProcessfirmVisible = ref(false);

const process = reactive({
  team: "",
  head: "",
  batchId: route.query.BatchId, // 批次id
  processId: 0, // 深加工id
});

const createProcess = () => {
  dialogProcessfirmVisible.value = true;
  axios
    .post("https://localhost:7238/api/Process/CreateProcess", process)
    .then((res) => {
      if (res.data.code == 100) {
        ElMessage.success("新增成功");
        getProcessList();
        dialogProcessfirmVisible.value = false;
        // getProcessList();
      } else if (res.data.code == 206) {
        ElMessage.success(res.data.msg);
        getProcessList();
        dialogProcessfirmVisible.value = false;
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};
const ProcessList = reactive({
  team: "",
  head: "",
  batchId: 0, // 批次id
  processId: 0, // 深加工id
});

/* const processFantian = () => {
  axios.post()
} */

//显示
// const Processs = reactive([]);
const getProcessList = () => {
  axios
    .get("https://localhost:7203/api/Process", {
      params: { batchId: route.query.BatchId },
    })
    .then((res) => {
      if (res.data.code == 200) {
        process.processId = res.data.data[0].processId;
        process.team = res.data.data[0].team;
        process.head = res.data.data[0].head;
        process.batchId = res.data.data[0].batchId;

        ProcessList.processId = res.data.data[0].processId;
        ProcessList.team = res.data.data[0].team;
        ProcessList.head = res.data.data[0].head;
        ProcessList.batchId = res.data.data[0].batchId;
      }
    });
};


// 统一处理上传响应  handleUploadSuccess
const handleProcessUploadSuccess = (
  response: any,
  uploadFile: UploadFile
) => {
  console.log("完整响应:", response); // 调试关键点

  // 根据实际响应结构调整（常见情况处理）
  let imgUrl = "";
  let imgname = ""; //图片名称
  // 情况1：响应直接返回字符串URL
  if (typeof response === "string") {
    imgUrl = response;
    imgname = uploadFile.name;
  }
  // 情况2：响应为 { data: { url: ... } }
  else if (response?.data?.url) {
    imgUrl = response.data.url;
    // alert(imgUrl);
  }
  // 情况3：响应为 { url: ... }
  else if (response?.url) {
    imgUrl = response.url;
  }

  // 校验是否获取到有效URL
  if (imgUrl) {
    // alert(imgUrl);
    // 补全URL前缀（如果返回的是相对路径）
    if (!imgUrl.startsWith("http")) {
      imgUrl = `http://localhost:5004${imgUrl}`;
    }

    imgs.value.imgType = imgUrl;
    imgs.value.imgName = imgname;
    // 提交到后端
    submitToBackend();
  } else {
    ElMessage.error("无法解析图片地址");
  }
};
// 
const falseProcessFirms = ref([])

//食品安全图片
const getProcessFirmsIntegrateImg = () => {
    axios
    .get("https://localhost:7203/api/IntegrateImg/GetProcessFirmsImg", {
      params: {
        BatchId: route.query.BatchId?.toString() || "",
        ImgName: "食品安全",
      },
    })

    .then((res) => {
      // imagelist.value=res.data.dataco
      // console.log(res.data.data[0], "屠宰信息图片");
      falseProcessFirms.value = res.data.data.map((img: any) => ({
        url: img.imgType,
        id: img.integrateImgsId,
        data: { integrateImgsId: img.integrateImgsId }, // 将 imaId 存入 data
      }));
      // console.log(falseSlaughterFirms.value, "屠宰信息图片1111");
    });
}
//#endregion
</script>

<style scoped>
.product-detail-container {
  padding: 20px;
}

.top-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.product-image {
  margin-right: 20px;
  margin-top: -170px;
}

.product-basic {
  margin-right: 40px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.breeding-info {
  gap: 20px;
}

.info-item {
  margin-bottom: 10px;
}

.health-care,
.inspection,
.enterprise-info,
.enterprise-photo {
  margin-top: 20px;
}

.upload-box {
  width: 100px;
  height: 100px;
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  cursor: pointer;
}

.health-care-container {
  padding: 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
}

.el-input {
  width: 95%;
}

:deep(.el-table__cell) {
  padding: 8px 0;
}
</style>